package models

import (
	"errmsg"
	"errors"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"time"
	"tools"
)

type Notepad struct {
	Id         string `orm:"column(id);pk" json:"id" form:"id"`
	UserId     string `orm:"column(user_id)" json:"user_id" form:"user_id"`
	Goods      string `orm:"column(goods)" json:"goods" form:"goods"`
	Where      string `orm:"column(where)" json:"where" form:"where"`
	CreateTime int64  `orm:"column(create_time)" json:"create_time" form:"create_time"`
}

func (m *Notepad) TableName() string {
	return "notepad"
}

func init() {
	orm.RegisterModel(new(Notepad))
}

func NewNotepad() *Notepad {
	return &Notepad{}
}

// 判断物品是否已经存在 如有id 怎排除id
func IsExistsNotePadByGoods(uid, g string, id ...string) (bool, error) {
	var (
		count int
		vals  []interface{}
	)
	sql := `SELECT count(id) FROM notepad WHERE goods = ? AND user_id = ?`
	vals = append(vals, g, uid)
	if len(id) > 0 {
		sql += " and id != ?"
		vals = append(vals, id[0])
	}
	if err := orm.NewOrm().Raw(sql).SetArgs(vals).QueryRow(&count); err != nil {
		logs.Error(err)
		return false, err
	}
	if count == 0 {
		return false, nil
	}
	return true, nil
}

func GetNotePadByGoods(uid, g string) (*Notepad, error) {
	var (
		np  = &Notepad{}
		err error
		sql string
	)

	sql = "SELECT * FROM `notepad` WHERE `goods` = ? AND `user_id` = ?"
	err = orm.NewOrm().Raw(sql, g, uid).QueryRow(np)
	if err == orm.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		logs.Error("GetNotePadByGoods:", err)
		return nil, errmsg.ErrResponseSystem
	}

	return np, nil
}

func AddNotepad(np *Notepad) error {

	var (
		is  bool
		err error
	)
	if is, err = IsExistsNotePadByGoods(np.UserId, np.Goods); err != nil {
		logs.Error("AddNotepad error:", err)
		return errmsg.ErrResponseSystem
	}
	if is {
		err = errors.New("物品已记录, 不能重复添加")
		logs.Info("AddNotepad error:", err)
		return err
	}

	np.Id = tools.GUUID()
	np.CreateTime = time.Now().Unix()

	// 数据入库
	if _, err = orm.NewOrm().Insert(np); err != nil {
		logs.Error("AddNotepad error:", err)
		return errmsg.ErrResponseSystem
	}

	return nil
}

func UpdateNotepad(np *Notepad) error {
	var (
		is  bool
		err error
	)

	if is, err = IsExistsNotePadByGoods(np.UserId, np.Goods, np.Id); err != nil {
		logs.Error("UpdateNotepad error:", err)
		return errmsg.ErrResponseSystem
	}
	if is {
		err = errors.New("物品已记录, 不能重复")
		logs.Info("UpdateNotepad error:", err)
		return err
	}

	// 数据入库
	if _, err = orm.NewOrm().Update(np); err != nil {
		logs.Error("UpdateNotepad error:", err)
		return errmsg.ErrResponseSystem
	}

	return nil
}

func GetNotepadById(id string) (*Notepad, error) {
	np := &Notepad{Id: id}
	err := orm.NewOrm().Read(np)
	if err == orm.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		logs.Error(err)
		return nil, err
	}
	return np, nil
}

func GetAllNotepadByUid(uid string, page int) ([]*Notepad, error) {
	var (
		ls  []*Notepad
		err error
		qs  orm.QuerySeter
	)

	qs = orm.NewOrm().QueryTable(NewNotepad().TableName()).Filter("user_id", uid).OrderBy("-create_time")

	if page > 0 {
		row := beego.AppConfig.DefaultInt("page_limit", 20)
		start := (page - 1) * row
		qs = qs.Limit(row).Offset(start)
	}

	if _, err = qs.All(&ls); err != nil {
		logs.Error("GetNotepadByUid error:", err)
		return nil, errmsg.ErrResponseSystem
	}

	if len(ls) == 0 {
		return nil, nil
	}

	return ls, nil
}

func DelNotepad(uid, id string) error {
	_, err := orm.NewOrm().QueryTable(NewNotepad().TableName()).Filter("id", id).Filter("user_id", uid).Delete()
	if err != nil {
		logs.Error("DelNotepad error:", err)
		return errmsg.ErrResponseSystem
	}
	return nil
}
